<template>
	<div class="phone-pack-mobile">
		<van-popup v-model="visible" position="bottom" :style="{ height: '100%' }">
			<div class="popup flex-column">
				<van-nav-bar
					:title="pageKey == 1 ? '号码包' : '微信库'"
					left-arrow
					@click-left="close"
				/>
				<!-- 号码包 -->
				<template v-if="pageKey == 1">
					<div class="search">
						<van-search
							v-model="rightData.search"
							placeholder="请输入微信号"
							shape="round"
							@search="onRightSearch"
						/>
					</div>
					<div class="flex-1 popup-body" ref="container">
						<ul class="list">
							<van-checkbox-group
								v-model="rightData.multipleSelection"
								icon-size="13"
								checked-color="#156DFF"
							>
								<li
									class="flex flex-align-center list-item"
									v-for="(item, index) in rightDataShowTable"
									:key="index"
								>
									<van-checkbox :name="item.id" shape="square">
										<div class="list-item_info">
											<div>
												<span>{{ item.wechat_number }}</span>
												<span
													class="list-item_info--name"
													v-if="item.user_name"
													>（{{ item.user_name }}）</span
												>
											</div>
											<div
												class="list-item_info--status"
												:class="[item.status == 1 ? '' : 'active']"
											>
												{{ item.status == 1 ? "暂停中" : "使用中" }}
											</div>
										</div>
									</van-checkbox>
								</li>
							</van-checkbox-group>
						</ul>
					</div>
						<!-- 按钮 -->
						<div class="btn-wrap">
							<van-button
								class="btn-list"
								v-for="(item, index) in rightData.btnList"
								:key="index"
								@click="onOperate(item)"
								:loading="confirmLoading"
								:class="[item.class]"
							>
								{{ item.label }}
							</van-button>
						</div>
				</template>
				<!-- 微信库 -->
				<template v-else>
					<div class="search">
						<van-search
							v-model="leftData.search"
							placeholder="请输入微信号"
							shape="round"
							@search="onLeftSearch"
						/>
					</div>
					<div class="flex-1 popup-body" ref="container">
						<van-list
							v-model="leftData.loading"
							:finished="leftData.finished"
							finished-text="没有更多了"
							@load="getLeftList"
						>
							<van-checkbox-group
								v-model="leftData.multipleSelection"
								icon-size="13"
								checked-color="#156DFF"
							>
								<li
									class="flex flex-align-center list-item"
									v-for="(item, index) in leftData.table"
									:key="index"
								>
									<van-checkbox :name="item.id" :disabled="!item.isDisabled" shape="square">
										<div class="list-item_info">
											<div>
												<span>{{ item.wechat_number }}</span>
												<span
													class="list-item_info--name"
													v-if="item.user_name"
													>（{{ item.user_name }}）</span
												>
											</div>
											<div
												class="list-item_info--status"
												:class="[item.isDisabled ? '' : 'active']"
											>
												{{ item.isDisabled ? "未上架" : "已上架" }}
											</div>
										</div>
									</van-checkbox>
								</li>
							</van-checkbox-group>
						</van-list>
					</div>
						<!-- 按钮 -->
						<div class="btn-wrap wx-store-btn">
							<van-button
								class="btn-list"
								v-for="(item, index) in leftData.btnList"
								:key="index"
								:loading="confirmLoading"
								@click="onOperate(item)"
								:class="[item.class]"
							>
								{{ item.label }}
							</van-button>
						</div>
				</template>
			</div>
		</van-popup>
	</div>
</template>

<script>
	import Vue from 'vue';
	import { Popup, NavBar, Search, List, Checkbox, CheckboxGroup, Toast, Button } from "vant";

	Vue.use(Toast);
	export default {
		components: {
			VanPopup: Popup,
			VanNavBar: NavBar,
			VanSearch: Search,
			VanList: List,
			VanCheckbox: Checkbox,
			VanCheckboxGroup: CheckboxGroup,
			VanButton: Button
		},
		data() {
			return {
				visible: false,
				saving: false,
				pageKey: 1,

				leftDataCopy: {
					search: "",
					loading: false,
					finished: false,
					page: 1,
					size: 10,
					total: 0,
					table: [],
					btnList: [
						{
							label: "返回",
							key: "numberStore"
						},
						{
							label: "上架",
							class: "active",
							key: "takeUp"
						}
					],
					multipleSelection: []
				},
				leftData: {},

				rightDataCopy: {
					search: "",
					keyword: "",
					loading: false,
					page: 1,
					size: 10,
					total: 0,
					table: [],
					btnList: [
						{
							label: "微信库",
							key: "wxStore"
						},
						{
							label: "下架",
							key: "takeDown"
						},
						{
							label: "暂停",
							key: "stop"
						},
						{
							label: "开启",
							class: "active",
							key: "start"
						}
					],
					multipleSelection: []
				},
				rightData: {},
				info: {},

				operator: 4,
				confirmLoading: false
			};
		},
		computed: {
			transferRightDisable() {
				return this.leftData.multipleSelection?.length == 0 ?? true;
			},
			transferLeftDisable() {
				return this.rightData.multipleSelection?.length == 0 ?? true;
			},
			// 右侧列表搜索筛选
			rightDataShowTable() {
				let rightTable = this.rightData?.table ?? [];

				if (this.rightData.keyword) {
					rightTable = rightTable.filter(
						(e) => e.wechat_number.indexOf(this.rightData.keyword) > -1
					);
				}

				return rightTable;
			}
		},
		methods: {
			open(info = {}) {
				this.info = info;
				this.leftData = JSON.parse(JSON.stringify(this.leftDataCopy));
				this.rightData = JSON.parse(JSON.stringify(this.rightDataCopy));

				this.visible = true;

				this.getLeftList();
				this.getRightList();
			},
			close() {
				this.pageKey = 1
				this.visible = false;
			},
			// 左侧操作
			getLeftList() {
				this.leftData.loading = true;
				const query = {
					supplier_id: this.info.id,
					page: this.leftData.page,
					size: this.leftData.size,
					wechat_number: this.leftData.search
				};
				this.$service.accountManage
					.wechatPoolList(query)
					.then((res) => {
						console.info("左边的数据res", res);
						if (this.leftData.page === 1) {
							this.leftData.table = res.data;
						} else {
							this.leftData.table = [...this.leftData.table, ...res.data];
						}
						this.leftData.total = res.total;
						this.leftData.page = res.page + 1;

						if (this.leftData.table.length >= res.total) {
							this.leftData.finished = true
						} else {
							this.leftData.finished = false
						}

						this.formatData();
					})
					.catch(e => {
						Toast.fail(e);
					})
					.finally(() => {
						this.leftData.loading = false;
					});
			},
			onLeftSearch() {
				this.leftData.page = 1;
				this.getLeftList();
			},

			// 右侧操作
			getRightList() {
				this.rightData.loading = true;
				const query = {
					supplier_id: this.info.id
				};
				this.$service.accountManage
					.wechatDetail(query)
					.then((res) => {
						this.rightData.table = res;
						this.rightData.total = res.length;

						this.formatData();
					})
					.catch(e => {
						Toast.fail(e);
					})
					.finally(() => {
						this.rightData.loading = false;
					});
			},
			onRightSearch() {
				// this.rightData.page = 1;
				this.rightData.keyword = JSON.parse(JSON.stringify(this.rightData.search));
				console.info("this.rightData.keyword", this.rightData.keyword)
			},
			onStartOrStop(type) {
				if (this.rightData.multipleSelection.length == 0) {
					Toast.fail("请至少勾选一个！");
					return false;
				}

				let promptArr = [];
				let isRepeat = false;
				const h = this.$createElement;

				let wechatIdArr = [];
				let wechatNumberArr = [];
				let addWechatId = [];
				let userIds = []
				this.rightData.multipleSelection.forEach(e => {
					const data = this.rightData.table.find(item => item.id == e)

					if (
						data.add_wechat_supplier_id &&
						data.add_wechat_supplier_id != data.supplier_id
					) {
						isRepeat = true;
						promptArr.push(
							h(
								"p",
								null,
								`“${data.wechat_number}” 已绑定广告账户账号 “${data.add_wechat_supplier_account}”`
							)
						);
					}

					wechatIdArr.push(data.wechat_id)
					wechatNumberArr.push(data.wechat_number)
					addWechatId.push(data.add_wechat_id)
					userIds.push(data.user_id)
				})

				// this.rightData.multipleSelection.forEach((item) => {
				// 	if (
				// 		item.add_wechat_supplier_id &&
				// 		item.add_wechat_supplier_id != item.supplier_id
				// 	) {
				// 		isRepeat = true;
				// 		promptArr.push(
				// 			h(
				// 				"p",
				// 				null,
				// 				`“${item.wechat_number}” 已绑定广告账户账号 “${item.add_wechat_supplier_account}”`
				// 			)
				// 		);
				// 	}
				// });

				this.operator = type;
				// const wechatIdArr = this.rightData.multipleSelection.map((e) => e.wechat_id);
				// const wechatNumberArr = this.rightData.multipleSelection.map((e) => e.wechat_number);
				// const addWechatId = this.rightData.multipleSelection.map((e) => e.add_wechat_id);

				// 有广告账户账号重复的时候
				if (isRepeat && type === 1) {
					this.$msgbox({
						title: "提示",
						message: h("p", null, [
							h(
								"p",
								{
									style: "color: rgb(250, 51, 84); font-size: 16px; margin-bottom: 10px"
								},
								"以下账号已经绑定别的广告账户账号，是否多开？"
							),
							...promptArr
						]),
						customClass: "wechat-number-confirm",
						showCancelButton: true,
						closeOnClickModal: false,
						type: "warning",
						callback: (e) => {
							if (e == "confirm") {
								this.submit(wechatIdArr, wechatNumberArr, addWechatId, userIds);
							}
						}
					});
					return false;
				}

				this.submit(wechatIdArr, wechatNumberArr, addWechatId, userIds);
			},

			// 公共操作
			formatData() {
				const rightWeChatArr = this.rightData?.table?.map((e) => e.wechat_number) ?? [];

				console.info("rightWeChatArr", rightWeChatArr);
				if (rightWeChatArr.length == 0) {
					return false;
				}

				this.leftData.table = this.leftData.table.map((item) => {
					return {
						...item,
						isDisabled: !rightWeChatArr.includes(item.wechat_number)
					};
				});

				console.info("this.leftData.table", this.leftData.table);
			},
			// 下架
			onTransferRight() {
				if (this.rightData.multipleSelection.length == 0) {
					Toast.fail("请至少勾选一个！");
					return false;
				}

				this.operator = 3;

				let wechatIdArr = [];
				let wechatNumberArr = [];
				let userIds = []
				this.rightData.multipleSelection.forEach(e => {
					const data = this.rightData.table.find(item => item.id == e)

					wechatIdArr.push(data.wechat_id)
					wechatNumberArr.push(data.wechat_number)
					userIds.push(data.user_id)
				})

				this.submit(wechatIdArr, wechatNumberArr, [], userIds);
			},
			// 上架
			onTransferLeft() {
				if (this.leftData.multipleSelection.length == 0) {
					Toast.fail("请至少勾选一个！");
					return false;
				}

				this.operator = 4;

				let wechatIdArr = [];
				let wechatNumberArr = [];
				this.leftData.multipleSelection.forEach(e => {
					const data = this.leftData.table.find(item => item.id == e)

					wechatIdArr.push(data.wechat_id)
					wechatNumberArr.push(data.wechat_number)
				})

				// const wechatIdArr = multipleSelection.map((e) => e.wechat_id);
				// const wechatNumberArr = multipleSelection.map((e) => e.wechat_number);

				this.submit(wechatIdArr, wechatNumberArr);
			},
			// 按钮操作
			onOperate(e) {
				if (e.key == 'wxStore') {
					this.pageKey = 2
				}
				if (e.key == 'takeDown') {
					this.onTransferRight()
				}
				if (e.key == 'stop') {
					this.onStartOrStop(2)
				}
				if (e.key == 'start') {
					this.onStartOrStop(1)
				}

				if (e.key == 'numberStore') {
					this.pageKey = 1
				}
				if (e.key == 'takeUp') {
					this.onTransferLeft()
				}
			},
			/**
			 * 公共提交操作
			 * @param {Object} wechat_ids 微信id
			 * @param {Object} wechat_number 微信号
			 * @param {Object} add_wechat_ids 加微码id
			 * @param {Object} user_ids 用户id
			 */
			submit(wechat_ids = [], wechat_number = [], add_wechat_ids = [], user_ids = []) {
				this.confirmLoading = true;
				const query = {
					supplier_id: this.info.id,
					operator: this.operator,
					wechat_ids: wechat_ids,
					wechat_number: wechat_number,
					add_wechat_ids: add_wechat_ids,
					user_ids: user_ids
				};
				this.$service.accountManage
					.wechatUpdate(query)
					.then((res) => {
						// this.$message.success("操作成功!");
						Toast.success('操作成功！');

						this.leftData.multipleSelection = []
						this.rightData.multipleSelection = []

						this.getRightList();
					})
					.finally(() => {
						this.confirmLoading = false;
					});
			}
		}
	};
</script>

<style lang="scss" scoped>
	::v-deep {
		.van-nav-bar .van-icon {
			color: #333 !important;
		}
		.el-input.is-disabled .el-input__inner {
			background-color: transparent;
		}
	}
	.phone-pack-mobile {
		.item-content {
			align-items: center;
			padding-bottom: 0.1rem;
			border-bottom: 1px solid #dfdfdf;
			.icon {
				color: #999;
			}
		}
		.popup {
			height: 100%;
			overflow: hidden;
			.search {
				padding-right: 4px;
			}
			&-body {
				position: relative;
				overflow: auto;
				background: #fff;
				box-sizing: border-box;
				border-top: 1px solid #dfdfdf;

				margin-bottom: 50px;

				.list-item {
					height: 60px;
					padding: 0 15px;
					border-bottom: 1px solid #dfdfdf;
					.van-checkbox {
						width: 100%;
						::v-deep .van-checkbox__label {
							flex: 1;
						}
					}
					&_info {
						flex: 1;
						display: flex;
						align-items: center;
						justify-content: space-between;
						font-size: 14px;
						&--name {
							color: #666;
						}
						&--status {
							font-size: 12px;
							color: #999;
							&.active {
								color: $primary;
							}
						}
					}
				}
			}
		}
		.btn-wrap {
			// position: absolute;
			position: fixed;

			bottom: 0;
			width: 100%;
			height: 48px;
			display: flex;
			align-items: center;
			justify-content: space-evenly;
			border-top: 0.6px solid #dfdfdf;
			background-color: #fff;
			.btn-list {
				width: 74px;
				height: 30px;
				line-height: 30px;
				border: 0.6px solid #999;
				text-align: center;
				border-radius: 30px;
				font-size: 13px;
				&.active {
					color: #fff;
					border-color: $primary;
					background-color: $primary;
				}
			}
			&.wx-store-btn {
				justify-content: flex-end;
				.btn-list {
					margin-right: 16px;
				}
			}
		}
	}
</style>
